# -*- coding: utf-8 -*-
# Created by liangfuting on 2020/8/19
# Copyright (c) 2020 liangfuting. All rights reserved.
from django.urls import path
from django.shortcuts import render, redirect,reverse,HttpResponse
from stark.service.v1 import StarkHandler,BootStrapModelForm,get_datetime_text
from stark.forms.widgets import DateTimePickerInput
from django.utils.safestring import mark_safe
from web import models


class ConsultRecordModelForm(BootStrapModelForm):
    class Meta:
        model=models.ConsultRecord
        fields=["note",]
        widgets={
            'date':DateTimePickerInput,
        }

class ConsultRecordHandler(StarkHandler):
    list_display=['customer','consultant',get_datetime_text('跟进日期','date'),'note']
    model_form_class = ConsultRecordModelForm
    change_list_template = 'web/consult_record.html'

    def get_urls(self):
        #若子类继承，可修改返回列表值
        # print(self.get_add_url_name,self.get_list_url_name,self.get_edit_url_name,self.get_del_url_name)
        patterns=[]
        #原始方法
        # patterns.append(path('list/',self.list_view,name="{}_{}_list".format(self.app_label, self.model_name)))
        # patterns.append(path('add/', self.add_view, name="{}_{}_add".format(self.app_label, self.model_name)))
        # patterns.append(path('edit/<int:pk>/', self.change_view, name="{}_{}_edit".format(self.app_label, self.model_name)))
        # patterns.append(path('delete/<int:pk>/', self.delete_view, name="{}_{}_delete".format(self.app_label, self.model_name)))
        patterns.append(path('list/<int:customer_id>/',self.wapper(self.list_view),name=self.get_list_url_name))
        patterns.append(path('add/<int:customer_id>/', self.wapper(self.add_view), name=self.get_add_url_name))
        patterns.append(path('edit/<int:customer_id>/<int:pk>/', self.wapper(self.change_view), name=self.get_edit_url_name))
        patterns.append(path('delete/<int:customer_id>/<int:pk>/', self.wapper(self.delete_view), name=self.get_del_url_name))
        # print(self.extra_urls())
        patterns.extend(self.extra_urls())
        # print(patterns)
        return patterns

    def get_query_set(self,request,*args,**kwargs):

        # print(request.session.keys())
        # if 'user_info' not in request.session:
        #     # print(reverse('login'))
        #     return redirect(reverse('login'))
        customer_id=kwargs.get('customer_id')

        user_id = request.session['user_info']['id']
        # print(customer_id,user_id)
        #客户的顾问ID是当前用户时，才能访问跟进记录
        return self.model_class.objects.filter(customer_id=customer_id,customer__consultant_id=user_id)

    def save(self,request,form,is_update,*args,**kwargs):
        user_id = request.session['user_info']['id']
        customer_id = kwargs.get('customer_id')
        object_exists=models.Customer.objects.filter(id=customer_id,consultant_id=user_id).exists()
        if not object_exists:
            return HttpResponse('非法操作')
        if not is_update:
            #新增用户
            form.instance.consultant_id=user_id
            form.instance.customer_id=customer_id
        #更新用户信息
        form.save()

    # def get_add_btn(self,request,*args,**kwargs):
    #     #子类可继承函数，预留此钩子函数
    #     if self.has_add_btn:
    #         # customer_id=kwargs.get('customer_id')
    #         target_url=self.reverse_add_url(*args,**kwargs)
    #         # reverse("stark:web_consultrecord_add", kwargs={'customer_id': customer_id})
    #         return "<a class='btn btn-success' href='{}'>添加</a>".format(target_url)
    #     return None

    def get_change_object(self,request,pk,*args,**kwargs):
        user_id = request.session['user_info']['id']
        customer_id = kwargs.get('customer_id')
        # print(user_id,customer_id,args,kwargs)
        return self.model_class.objects.filter(pk=pk,customer_id=customer_id,customer__consultant_id=user_id).first()

    def delete_object(self,request,pk,*args,**kwargs):
        user_id = request.session['user_info']['id']
        customer_id = kwargs.get('customer_id')
        # print(user_id, customer_id, args, kwargs)
        record_queryset=self.model_class.objects.filter(pk=pk,customer_id=customer_id,customer__consultant_id=user_id).first()
        if not record_queryset:
            return HttpResponse('要删除的记录不存在，请重新选择')
        record_queryset.delete()



    def display_edit_del(self,obj=None,is_header=None,*args,**kwargs):
        if is_header:
            return '操作'
        # print(kwargs)
        customer_id = kwargs.get('customer_id')
        edit_url=self.reverse_change_url(pk=obj.pk,customer_id=customer_id)
        del_url = self.reverse_del_url(pk=obj.pk,customer_id=customer_id)
        return mark_safe("<a href='{}'><i class='fa fa-edit' aria-hidden='true'></i> 编辑</a> <a href='{}'><i class='fa fa-trash-o'></i> 删除</a>".format(edit_url,del_url))



